package com.whxy02.tolearn.app.controller;

import com.whxy02.tolearn.app.beans.Card;
import com.whxy02.tolearn.app.beans.History;
import com.whxy02.tolearn.app.beans.User;
import com.whxy02.tolearn.app.resultObject.ResultState;
import com.whxy02.tolearn.app.resultObject.UserResultType;
import com.whxy02.tolearn.app.service.*;
import com.whxy02.tolearn.app.utils.PackResult;
import com.whxy02.tolearn.app.utils.Upload;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("user")
public class UserPage {
    @Resource
    UserService userService;
    @Resource
    CardService cardService;
    @Resource
    HistoryService historyService;
    @Resource
    PackResult packResult;
    @Resource
    SubjectService subjectService;
    @Resource
    TagsService tagsService;
    @Resource
    Upload upload;
    @Resource
    RedisTemplate<String,Object> redisTemplate;


    @RequestMapping("/getUser")
    public User getUser(HttpServletRequest request){
        return  (User) request.getAttribute("user");
    }

    /**
     * 获取打卡信息、用户信息及做题历史信息
     * @param request
     * @return
     */
    @RequestMapping("userInfo")
    public Map<String,Object> getUserInfo(HttpServletRequest request){
        User user= (User) request.getAttribute("user");
        if(user==null){
            return packResult.doPackToMap(ResultState.NOT_LOGIN,null);
        }
        Integer userId=user.getUserId();
        UserResultType result=new UserResultType();
        try {
            Card card= cardService.getByUserId(userId);
            if(card==null){
                card=new Card();
                card.setUserId(userId);
                cardService.save(card);
            }
            result.setCardInfo(card);
            result.setUserInfo(user);
            return packResult.doPackToMap(ResultState.SUCCESS,result);

        } catch (Exception e) {
            return packResult.doPackToMap(ResultState.SERVER_ERR,e);
        }
    }

    /**
     *
     * @param request
     * @param birthDate
     * @param className
     * @param description
     * @param email
     * @param grade
     * @param name
     * @param phone
     * @param pwd
     * @param role
     * @param schoolName
     * @param sex
     * @param username
     * @return
     */
    @RequestMapping("/update")
    public Map<String,Object> changeInfo(HttpServletRequest request, @RequestParam(value = "birthDate",required = false,
            defaultValue = "")Date birthDate, @RequestParam(value = "className",required = false,defaultValue = "")String className
            , @RequestParam(value = "description",required = false,defaultValue = "")String description
            ,@RequestParam(value = "email",required = false,defaultValue = "")String email, @RequestParam(value = "grade"
            ,required = false,defaultValue = "")String grade, @RequestParam(value = "name",required = false
            ,defaultValue = "")String name, @RequestParam(value = "phone",required = false,defaultValue = "")String phone
            , @RequestParam(value = "pwd",required = false,defaultValue = "")String pwd, @RequestParam(value = "role",
            required = false,defaultValue = "")Integer role, @RequestParam(value = "schoolName",required = false,
            defaultValue = "")String schoolName,@RequestParam(value = "sex",required = false)Boolean sex
            , @RequestParam(value = "username",required = false,defaultValue = "")String username){
        User user= (User) request.getAttribute("user");
        /**
         * 获取前端修改的信息
         */
        if(birthDate!=null){
            user.setBirthDate(birthDate);
        }
        if(!className.equals("")){
            user.setClassName(className);
        }
        if(!description.equals("")){
            user.setDescription(description);
        }
        if(!email.equals("")){
            user.setEmail(email);
        }
        if(!grade.equals("")){
            user.setGrade(grade);
        }
        if(!name.equals("")){
            user.setName(name);
        }
        if(!phone.equals("")){
            user.setPhone(phone);
        }
        if(pwd.matches("\\w{6,20}")){
            user.setPwd(pwd);
        }
        if(role!=0){
            user.setRole(role);
        }
        if(!schoolName.equals("")){
            user.setSchoolName(schoolName);
        }
        if(username.matches("\\w{3,20}")){
            user.setUsername(username);
        }
        user.setSex(sex);

        try {
            userService.change(user);

            return packResult.doPackToMap(ResultState.SUCCESS);
        } catch (Exception e) {
            return packResult.doPackToMap(ResultState.SERVER_ERR,e);
        }
    }


    @RequestMapping("/search/{userId}")
    public Map<String,Object> searchUser(@PathVariable("userId")Integer userId){
        try {
            User user= userService.getById(userId);
            if(user!=null){
                return packResult.doPackToMap(ResultState.SUCCESS,user);
            }else {
                return packResult.doPackToMap(ResultState.USER_NOT_FOUND);
            }
        } catch (Exception e) {

            e.printStackTrace();
           return packResult.doPackToMap(ResultState.SERVER_ERR,e);
        }

    }

    @RequestMapping("/history")
    public Map<String,Object> getHistory(HttpServletRequest request){

        User user= (User) request.getAttribute("user");
        try {
            List<History> histories= historyService.getByUserId(user.getUserId());
            for(History history:histories){
                if (history!=null){
                    history.setSubject(subjectService.getById(history.getSubjectId()).getSubjectName());
                    history.setTags(tagsService.getById(history.getTagsId()).getTagsName());
                }
            }
            return packResult.doPackToMap(ResultState.SUCCESS,histories);
        } catch (Exception e) {
            e.printStackTrace();
            return packResult.doPackToMap(ResultState.SERVER_ERR);
        }
    }

    @RequestMapping("/changeImage")
    public String changeImage(HttpServletRequest request, @RequestParam("file")MultipartFile file) {

        User user= (User) request.getAttribute("user");

        user.setUserImage(upload.upload(file,"images","user",user.getUserId()));
//
        Cookie[] cookies=request.getCookies();
        for(Cookie cookie:cookies){
            if(cookie.getName().equals("sessionID")) {
                redisTemplate.opsForValue().set("user:"+cookie.getValue(),user,60*60*2,TimeUnit.SECONDS);
            }
        }
        try {
            userService.change(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return user.getUserImage();
    }
}
